package com.dark.common.repository.dbutils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.dbutils.QueryRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.dark.common.repository.exception.DBException;
 
/**
 * 数据库管理
 * @author Winter Lau
 * @date 2010-2-2 下午10:18:50
 */
@Component
public class DBManager {
 
	private static Logger logger = LoggerFactory.getLogger(DBManager.class);
	
    private static DruidDataSource dds ;
    
    private static QueryRunner queryRunner ;
    
    static {
        initDataSource(loadPropFile("resources.properties"));
    }
 
    /**
     * 初始化连接池
     * @param props
     * @param show_sql
     */
    private final static void initDataSource(Properties dbProperties) {
        try {
            if(dbProperties == null){
                dbProperties = new Properties();
                dbProperties.load(DBManager.class.getResourceAsStream("resources.properties"));
            }
            dds = (DruidDataSource) DruidDataSourceFactory.createDataSource(dbProperties) ;
            queryRunner = new QueryRunner(dds) ;
        } catch (Exception e) {
        	logger.error("初始化连接池异常：{}", e.getMessage()) ;
            throw new DBException(e.getMessage());
        }
    }
     
    public static DruidDataSource getDataSource() {
		return dds ;
	}
	
	public static DruidPooledConnection getConnection() {
		try {
			return dds.getConnection() ;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
    
	public static QueryRunner getQueryRunner() {
		return queryRunner ;
	}
	
    /**
	 * 加载属性文件
	 * @param fullname 文件名称
	 * @return
	 */
	public static Properties loadPropFile(String fullname) {
		try {
			ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader() ;
			InputStream resourceAsStream = contextClassLoader.getResourceAsStream(fullname) ;
			Properties prop = System.getProperties() ;
			prop.load(resourceAsStream) ;
			
			return prop ;
		} catch (IOException e) {
			throw new DBException("DBManager加载数据库配置文件异常：" + e.getMessage()) ;
		}
	}
     
}